<!DOCTYPE html>
<html>
<head>
    <title>库存信息录入</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!-- Bootstrap CSS -->
    <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="../static/bootstrap/icons/bootstrap-icons.css" rel="stylesheet">
    <style>
        .stock-form {
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .required::after {
            content: " *";
            color: #d32f2f;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #2e7d32;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 10px 0;
        }
        .price-input {
            text-align: right;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1000px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1000px; margin: 0 auto 20px auto; padding: 0 20px;">库存信息录入</h2>

    <!-- 产品类型选择器 -->
    <div style="max-width: 1000px; margin: 0 auto 20px auto; padding: 0 20px;">
        <div class="form-group">
            <label class="required">产品类型</label>
            <select id="product_type" name="product_type" required onchange="changeProductType()">
                <option value="jade">玉石产品</option>
                <option value="culture">文创产品</option>
            </select>
        </div>
    </div>

    <div id="loading" class="loading" style="display: none;">正在加载...</div>
    <div id="error" class="error" style="display: none;"></div>
    <div id="success" class="success" style="display: none;"></div>

    <form id="stockForm" class="stock-form">
        <!-- 隐藏字段用于存储产品类型 -->
        <input type="hidden" id="hidden_product_type" name="product_type" value="jade">
        <!-- 库存基本信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">库存编号</label>
                <input type="text" id="stock_id" name="stock_id" required placeholder="请输入唯一的库存编号">
            </div>
            <div class="form-group">
                <label>库存名称</label>
                <input type="text" id="stock_name" name="stock_name" placeholder="请输入库存名称">
            </div>
        </div>

        <!-- 产品关联信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">产品ID</label>
                <input type="text" id="product_id" name="product_id" required 
                       placeholder="请输入产品ID或名称进行搜索"
                       autocomplete="off">
                <div id="product_suggestions" style="display: none; position: absolute; z-index: 1000; 
                    background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; 
                    width: calc(100% - 2px); box-shadow: 0 2px 5px rgba(0,0,0,0.2);"></div>
            </div>
            <div class="form-group">
                <label>产品名称</label>
                <input type="text" id="product_name" name="product_name" placeholder="产品名称将自动填充" readonly>
            </div>
        </div>

        <!-- 产品图片显示区域 -->
        <div class="form-group" id="product_image_container" style="display: none; text-align: center;">
            <label>产品图片预览</label>
            <div style="margin-top: 10px;">
                <img id="product_image" src="" alt="产品图片" style="max-width: 200px; max-height: 200px; border: 1px solid #ccc; border-radius: 4px;">
            </div>
        </div>

        <!-- 库存数量 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">库存数量</label>
                <input type="number" step="1" id="quantity" name="quantity" value="1" class="price-input" min="0" required>
            </div>
        </div>

        <!-- 分类信息 -->
        <div class="form-row">
            <div class="form-group">
                <label>类型1分类</label>
                <select id="type_1" name="type_1">
                    <option value="">请选择类型1</option>
                </select>
            </div>
            <div class="form-group">
                <label>类型2分类</label>
                <select id="type_2" name="type_2">
                    <option value="">请选择类型2</option>
                </select>
            </div>
        </div>

        <!-- 成本信息 -->
        <div class="form-row">
            <div class="form-group">
                <label>材料成本 (元)</label>
                <input type="number" step="0.01" id="material_price" name="material_price" value="0.00" class="price-input" min="0">
            </div>
            <div class="form-group">
                <label>材料成本支付对象</label>
                <select id="material_payer" name="material_payer">
                    <option value="">请选择</option>
                    <option value="水母">水母</option>
                    <option value="栎伊">栎伊</option>
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>手工成本 (元)</label>
                <input type="number" step="0.01" id="manual_price" name="manual_price" value="0.00" class="price-input" min="0">
            </div>
            <div class="form-group">
                <label>手工成本支付对象</label>
                <select id="manual_payer" name="manual_payer">
                    <option value="">请选择</option>
                    <option value="水母">水母</option>
                    <option value="栎伊">栎伊</option>
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>运输成本 (元)</label>
                <input type="number" step="0.01" id="transfer_price" name="transfer_price" value="0.00" class="price-input" min="0">
            </div>
            <div class="form-group">
                <label>运输成本支付对象</label>
                <select id="transfer_payer" name="transfer_payer">
                    <option value="">请选择</option>
                    <option value="水母">水母</option>
                    <option value="栎伊">栎伊</optiono>
                    <option value="晓">晓</option>
                    <option value="骆">骆</option>
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>其他成本 (元)</label>
                <input type="number" step="0.01" id="other_price" name="other_price" value="0.00" class="price-input" min="0">
            </div>
            <div class="form-group">
                <label>其他成本支付对象</label>
                <select id="other_payer" name="other_payer">
                    <option value="">请选择</option>
                    <option value="水母">水母</option>
                    <option value="栎伊">栎伊</option>
                    <option value="晓">晓</option>
                    <option value="骆">骆</option>
                </select>
            </div>
        </div>

        <!-- 备注 -->
        <div class="form-group">
            <label>备注</label>
            <textarea id="comment" name="comment" placeholder="请输入备注信息"></textarea>
        </div>

        <button type="submit" class="submit-btn">提交库存信息</button>
    </form>

    <script src="../static/js/common.js"></script>
    <script>
        let allProducts = []; // 存储所有产品数据
        let allTypes = new Set(); // 存储所有类型数据
        
        // 产品类型切换函数
        function changeProductType() {
            const productType = document.getElementById('product_type').value;
            document.getElementById('hidden_product_type').value = productType;
            
            // 清空当前表单数据
            document.getElementById('product_id').value = '';
            document.getElementById('product_name').value = '';
            document.getElementById('stock_id').value = ''; // 清空库存编号
            document.getElementById('type_1').value = '';
            document.getElementById('type_2').value = '';
            hideProductImage();
            
            // 重新加载对应类型的产品数据
            loadProductData();
        }

        // 解析URL参数
        function getUrlParams() {
            const params = new URLSearchParams(window.location.search);
            return {
                product_id: params.get('product_id'),
                product_name: params.get('product_name'),
                product_type: params.get('product_type')
            };
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 加载产品数据和类型数据
            loadProductData();
            
            // 设置当前时间为默认值（如果需要）
            const now = new Date();
            
        // 检查URL参数并自动填充表单
        const params = getUrlParams();
        if (params.product_id) {
            // 延迟执行以确保产品数据已加载
            setTimeout(() => {
                document.getElementById('product_id').value = params.product_id || '';
                document.getElementById('product_name').value = params.product_name || '';
                document.getElementById('stock_name').value = params.product_name || '';
                
                // 设置产品类型
                if (params.product_type === '玉石产品') {
                    document.getElementById('product_type').value = 'jade';
                    document.getElementById('hidden_product_type').value = 'jade';
                }
                
                // 触发产品信息更新
                updateProductInfoFromId(params.product_id);
            }, 500);
        }
            
            // 表单提交处理
            document.getElementById('stockForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const data = Object.fromEntries(formData.entries());
                
                // 添加时间戳
                data.created_at = new Date().toISOString();
                data.updated_at = new Date().toISOString();
                
                // 根据产品类型设置type_1和type_2
                const productType = document.getElementById('product_type').value;
                if (productType === 'culture') {
                    // 文创产品：type_1固定为"文创产品"，type_2使用产品数据中的type字段
                    data.type_1 = '文创产品';
                    // 如果type_2为空，使用type_1的值
                    if (!data.type_2) {
                        data.type_2 = data.type_1;
                    }
                }
                
                // 验证数据
                if (!validateForm(data)) {
                    return;
                }
                
                // 发送数据到后端
                submitStockData(data);
            });

            // 价格输入框格式化
            const priceInputs = document.querySelectorAll('.price-input');
            priceInputs.forEach(input => {
                input.addEventListener('blur', function() {
                    if (this.value === '') {
                        this.value = '0.00';
                    } else {
                        this.value = parseFloat(this.value).toFixed(2);
                    }
                });
                
                input.addEventListener('focus', function() {
                    if (this.value === '0.00') {
                        this.value = '';
                    }
                });
            });

            // 产品ID输入框模糊搜索功能
            initProductSearch();
        });

        // 初始化产品搜索功能
        function initProductSearch() {
            const productInput = document.getElementById('product_id');
            const suggestions = document.getElementById('product_suggestions');

            // 输入时进行模糊搜索
            productInput.addEventListener('input', function(e) {
                const searchText = e.target.value.trim();
                
                if (searchText.length < 1) {
                    suggestions.style.display = 'none';
                    return;
                }

                // 执行模糊搜索
                const matchedProducts = fuzzySearchProducts(searchText);
                showSuggestions(matchedProducts);
            });

            // 点击其他地方隐藏建议框
            document.addEventListener('click', function(e) {
                if (e.target !== productInput && e.target !== suggestions) {
                    suggestions.style.display = 'none';
                }
            });

            // 键盘导航
            productInput.addEventListener('keydown', function(e) {
                const visibleItems = suggestions.querySelectorAll('.suggestion-item');
                
                if (visibleItems.length === 0) return;

                const activeItem = suggestions.querySelector('.suggestion-item.active');
                let nextIndex = -1;

                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    if (!activeItem) {
                        nextIndex = 0;
                    } else {
                        nextIndex = Array.from(visibleItems).indexOf(activeItem) + 1;
                        if (nextIndex >= visibleItems.length) nextIndex = 0;
                    }
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    if (!activeItem) {
                        nextIndex = visibleItems.length - 1;
                    } else {
                        nextIndex = Array.from(visibleItems).indexOf(activeItem) - 1;
                        if (nextIndex < 0) nextIndex = visibleItems.length - 1;
                    }
                } else if (e.key === 'Enter' && activeItem) {
                    e.preventDefault();
                    selectSuggestion(activeItem);
                    return;
                } else if (e.key === 'Escape') {
                    suggestions.style.display = 'none';
                    return;
                }

                if (nextIndex >= 0) {
                    // 移除所有active类
                    visibleItems.forEach(item => item.classList.remove('active'));
                    // 添加active类到当前项
                    visibleItems[nextIndex].classList.add('active');
                }
            });
        }

        // 模糊搜索产品
        function fuzzySearchProducts(searchText) {
            if (!searchText) return [];
            
            const lowerSearchText = searchText.toLowerCase();
            return allProducts.filter(product => {
                // 搜索产品ID和产品名称
                const productId = product.product_id ? product.product_id.toLowerCase() : '';
                const productName = product.product_name ? product.product_name.toLowerCase() : '';
                
                return productId.includes(lowerSearchText) || 
                       productName.includes(lowerSearchText);
            });
        }

        // 显示搜索建议
        function showSuggestions(products) {
            const suggestions = document.getElementById('product_suggestions');
            
            if (products.length === 0) {
                suggestions.style.display = 'none';
                return;
            }

            suggestions.innerHTML = '';
            suggestions.style.display = 'block';

            products.forEach((product, index) => {
                const item = document.createElement('div');
                item.className = 'suggestion-item';
                item.style.padding = '8px 12px';
                item.style.cursor = 'pointer';
                item.style.borderBottom = '1px solid #eee';
                item.innerHTML = `
                    <div style="font-weight: bold;">${product.product_id}</div>
                    <div style="font-size: 12px; color: #666;">${product.product_name || '未命名'}</div>
                `;
                
                // 鼠标悬停效果
                item.addEventListener('mouseenter', function() {
                    this.style.backgroundColor = '#f5f5f5';
                    // 移除其他项的active类
                    suggestions.querySelectorAll('.suggestion-item').forEach(i => i.classList.remove('active'));
                    this.classList.add('active');
                });
                
                item.addEventListener('mouseleave', function() {
                    this.style.backgroundColor = '';
                });
                
                // 点击选择
                item.addEventListener('click', function() {
                    selectSuggestion(this);
                });
                
                suggestions.appendChild(item);
            });

            // 定位建议框
            const productInput = document.getElementById('product_id');
            const rect = productInput.getBoundingClientRect();
            suggestions.style.top = (rect.bottom + window.scrollY) + 'px';
            suggestions.style.left = rect.left + 'px';
        }

        // 选择建议项
        function selectSuggestion(item) {
            const productId = item.querySelector('div:first-child').textContent;
            const productInput = document.getElementById('product_id');
            const suggestions = document.getElementById('product_suggestions');
            
            productInput.value = productId;
            suggestions.style.display = 'none';
            
            // 触发产品信息更新
            updateProductInfoFromId(productId);
        }

        // 根据产品ID更新产品信息
        function updateProductInfoFromId(productId) {
            const product = allProducts.find(p => p.product_id === productId);
            const productType = document.getElementById('product_type').value;
            
            if (product) {
                document.getElementById('product_name').value = product.product_name || '';
                
                // 自动填充库存名称（如果当前库存名称为空）
                const stockNameInput = document.getElementById('stock_name');
                const currentStockName = stockNameInput.value;
                if (!currentStockName) {
                    stockNameInput.value = product.product_name || '';
                }
                
                // 自动生成库存编号（每次选择产品时都重新生成）
                const stockIdInput = document.getElementById('stock_id');
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const seconds = String(now.getSeconds()).padStart(2, '0');
                const timestamp = `${year}${month}${day}${hours}${minutes}${seconds}`;
                stockIdInput.value = `STK-${productId}-${timestamp}`;
                
                // 更新类型选择
                if (productType === 'culture') {
                    // 文创产品：type_1固定为"文创产品"，type_2使用产品数据中的type字段
                    document.getElementById('type_1').value = '文创产品';
                    if (product.type) {
                        document.getElementById('type_2').value = product.type;
                    }
                } else {
                    // 玉石产品：使用原有的逻辑
                    if (product.type_1) {
                        document.getElementById('type_1').value = product.type_1;
                    }
                    if (product.type_2) {
                        document.getElementById('type_2').value = product.type_2;
                    }
                }
                
                // 显示产品图片
                showProductImage(productId);
            }
        }

        // 加载产品数据
        function loadProductData() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const productType = document.getElementById('product_type').value;
            
            loading.style.display = 'block';
            error.style.display = 'none';

            // 根据产品类型选择不同的API端点
            const apiUrl = productType === 'culture' ? '/get_culture_product_list' : '/get_jade_product_list';
            
            fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if ((data.res === 'ok' || data.success) && data.data) {
                        allProducts = data.data;
                        initTypeOptions();
                    } else {
                        throw new Error('数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载产品数据失败: ' + error.message;
                });
        }


        // 初始化类型选项
        function initTypeOptions() {
            const productType = document.getElementById('product_type').value;
            const type1Select = document.getElementById('type_1');
            const type2Select = document.getElementById('type_2');
            
            if (productType === 'culture') {
                // 文创产品：type_1固定为"文创产品"且不可更改，type_2使用文创产品数据中的type字段
                type1Select.innerHTML = '<option value="文创产品">文创产品</option>';
                type1Select.disabled = true;
                
                // 收集文创产品的type字段
                const cultureTypes = new Set();
                allProducts.forEach(product => {
                    if (product.type) cultureTypes.add(product.type);
                });
                
                type2Select.innerHTML = '<option value="">请选择类型2</option>';
                cultureTypes.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type;
                    option.textContent = type;
                    type2Select.appendChild(option);
                });
                type2Select.disabled = true; // 类型2也不可修改
            } else {
                // 玉石产品：type_1和type_2都不可更改，从product_table中获取
                type1Select.disabled = true;
                type2Select.disabled = true;
                
                // 清空选项
                type1Select.innerHTML = '<option value="">请选择类型1</option>';
                type2Select.innerHTML = '<option value="">请选择类型2</option>';
                
                // 收集玉石产品的type_1和type_2字段
                const jadeType1s = new Set();
                const jadeType2s = new Set();
                
                allProducts.forEach(product => {
                    if (product.type_1) jadeType1s.add(product.type_1);
                    if (product.type_2) jadeType2s.add(product.type_2);
                });
                
                // 添加类型1选项
                jadeType1s.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type;
                    option.textContent = type;
                    type1Select.appendChild(option);
                });
                
                // 添加类型2选项
                jadeType2s.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type;
                    option.textContent = type;
                    type2Select.appendChild(option);
                });
            }
        }


        // 显示产品图片
        function showProductImage(productId) {
            const productImageContainer = document.getElementById('product_image_container');
            const productImage = document.getElementById('product_image');
            const productType = document.getElementById('product_type').value;
            
            if (productId) {
                // 根据产品类型使用不同的图片服务
                if (productType === 'culture') {
                    productImage.src = `/serve_jade_image?product_id=${productId}`;
                } else {
                    productImage.src = `/serve_jade_image?product_id=${productId}`;
                }
                productImageContainer.style.display = 'block';
            } else {
                hideProductImage();
            }
        }

        // 隐藏产品图片
        function hideProductImage() {
            const productImageContainer = document.getElementById('product_image_container');
            productImageContainer.style.display = 'none';
        }

        // 表单验证
        function validateForm(data) {
            const error = document.getElementById('error');
            error.style.display = 'none';

            // 检查必填字段
            if (!data.stock_id || data.stock_id.trim() === '') {
                showError('库存编号不能为空');
                return false;
            }

            if (!data.product_id || data.product_id.trim() === '') {
                showError('产品ID不能为空');
                return false;
            }

            // 检查库存数量是否为有效数字
            const quantity = parseFloat(data.quantity);
            if (isNaN(quantity) || quantity < 0) {
                showError('库存数量必须为有效的非负数');
                return false;
            }

            // 检查价格是否为有效数字
            const prices = ['material_price', 'manual_price', 'transfer_price', 'other_price'];
            for (const priceField of prices) {
                const value = parseFloat(data[priceField]);
                if (isNaN(value) || value < 0) {
                    showError('成本价格必须为有效的非负数');
                    return false;
                }
            }

            return true;
        }

        // 显示错误信息
        function showError(message) {
            const error = document.getElementById('error');
            error.style.display = 'block';
            error.textContent = message;
            
            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                error.style.display = 'none';
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const success = document.getElementById('success');
            success.style.display = 'block';
            success.textContent = message;
            
            // 3秒后自动隐藏成功信息
            setTimeout(() => {
                success.style.display = 'none';
            }, 3000);
        }

        // 提交库存数据
        function submitStockData(data) {
            const submitBtn = document.querySelector('.submit-btn');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';
            error.style.display = 'none';
            success.style.display = 'none';

            // 显示加载中
            const loading = document.getElementById('loading');
            loading.style.display = 'block';

            fetch('/deal_stock_and_settle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                loading.style.display = 'none';
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    showSuccess('库存信息保存成功！');
                    // 清空表单
                    document.getElementById('stockForm').reset();
                    // 重置价格字段为默认值
                    document.getElementById('material_price').value = '0.00';
                    document.getElementById('manual_price').value = '0.00';
                    document.getElementById('transfer_price').value = '0.00';
                    document.getElementById('other_price').value = '0.00';
                    // 清除图片预览
                    hideProductImage();
                } else {
                    throw new Error(result.message || '保存失败');
                }
            })
            .catch(error => {
                showError('保存失败: ' + error.message);
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交库存信息';
            });
        }
    </script>
</body>
</html>
